<script setup>
  import { toRef } from 'vue'

  import { uniqueId } from '@/helpers/utils'
  import { useField } from 'vee-validate'
  import FieldErrorMessage from './FieldErrorMessage.vue'
  import InputLabel from './InputLabel.vue'

  const props = defineProps({
    name: { type: String, required: true },
    label: { type: String, default: '' },
    value: { type: String || Number || Date, default: '' },
    description: { type: String, default: '' },
    required: { type: Boolean, default: false },
    css_class: { type: String, default: '' },
    editable: { type: Boolean, default: true },
    options: { type: Array, default: () => [] },
    idKey: { type: String, default: 'id' },
    labelKey: { type: String, default: 'label' },
    inline: { type: Boolean, default: false },
  })
  const emits = defineEmits(['changeValue', 'blurValue'])
  const tagId = uniqueId(props.name)

  const nameRef = toRef(props, 'name')
  // On récupère le schéma du formulaire parent
  const { value, errorMessage, handleBlur, handleChange, meta } =
    useField(nameRef)

  function onFieldChange(event) {
    handleChange(event)
    emits('changeValue', event.target.value)
  }
</script>
<template>
  <div
    class="form-group Integer"
    :class="{ 'has-error': meta.touched && !!errorMessage }"
  >
    <InputLabel :tagId="tagId" :required="required" :label="label" />
    <div class="radio">
      <div
        :class="{ radio_inline: !!inline }"
        v-for="(option, index) in options"
        :key="name + '-' + index"
      >
        <label id="tagId">
          <input
            type="radio"
            :name="name"
            :value="option[idKey]"
            :id="tagId + '-' + index"
            :checked="option[idKey] == value"
            autofocus="false"
            @input="onFieldChange"
            :disabled="!editable"
          />
          <span>{{ option[labelKey] }}</span>
        </label>
      </div>
    </div>
    <div class="help-block" v-if="description" v-html="description" />
    <FieldErrorMessage
      v-if="meta.touched && !!errorMessage"
      :message="errorMessage"
    />
  </div>
</template>
